package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.mapper.BannerMapper;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;

@Slf4j
@RestController
@Api(tags = "本地资源上传模块管理")
public class UploadController {
    @Value("${imagesPath}")
    private String dirPath;
    @Autowired
    private BannerMapper bannerMapper;

    @PostMapping("/upload")
    @ApiOperation(value = "图片资源上传", notes = "前端返回的picFile是一个MultipartFile的对象，需要将客户端的图片资源复制到服务器本地（/cs_maven_directory_name/src/main/resources/static/imgs/Xxx.xxx）,返回的url格式应为/imgs/xxx.xxx用于图片预览(代码在前端index.html中)")
    @ApiImplicitParam(name = "picFile", value = "图片文件",required = true)
    public String upload(@RequestParam(value = "picFile") MultipartFile picFile) {
        try {
            String type = picFile.getContentType().split("/")[0];
            if(type.equals("image")) {
                String url = "/imgs/upload-" + picFile.getOriginalFilename();
                File targetFile = new File(dirPath + url);
                picFile.transferTo(targetFile);
                log.debug("targetFile:" + targetFile.getAbsolutePath());
                return url;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @PostMapping("/remove")
    @ApiOperation(value = "图片缓存资源删除")
    @ApiImplicitParam(name = "url", value = "图片url", required = true)
    public void remove(String url){
        File targetFile = new File(dirPath + url);
        if(targetFile.exists()) targetFile.delete();
    }


}
